package hluck.me.srorage.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import hluck.me.srorage.sys.common.*;
import hluck.me.srorage.sys.domain.SysPermission;
import hluck.me.srorage.sys.domain.SysUser;
import hluck.me.srorage.sys.service.SysPermissionService;
import hluck.me.srorage.sys.service.SysRoleService;
import hluck.me.srorage.sys.service.SysUserService;
import hluck.me.srorage.sys.vo.SysPermissionVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysRoleService roleService;

    @RequestMapping("loadIndexLeftMenuJson")
    public DataGridView loadIndexLeftMenuJson(SysPermissionVo permissionVo){
        //查询所有菜单
        QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
        //设置只能查询菜单
        queryWrapper.eq("type", Constast.TYPE_MENU);
        queryWrapper.eq("available",Constast.AVAILABLE_TRUE);

        SysUser user = (SysUser) WebUtils.getSession().getAttribute("user");
        List<SysPermission> list= null;
        if (user.getType()==Constast.USER_TYPE_SUPPER){
            list=permissionService.list(queryWrapper);
        }else {
            //根据用户ID+角色+权限去查询
            Integer userId = user.getId();
            //根据用户Id查询角色
            List<Integer> ids = roleService.queryUserRoleIdsByUid(userId);
            //根据角色ID查询菜单id
            HashSet<Integer> pids = new HashSet<>();
            for (Integer rid : ids) {
                List<Integer> permissionIds = roleService.queryRolePermissionIdsByRid(rid);
                pids.addAll(permissionIds);
            }
            //根据菜单id查询菜单
            if (pids.size()>0) {
                queryWrapper.in("id",pids);
                list=permissionService.list(queryWrapper);
            }else {
                list=new ArrayList<>();
            }
        }

        ArrayList<TreeNode> treeNodes = new ArrayList<>();
        for (SysPermission permission : list) {
            Integer id=permission.getId();
            Integer pid=permission.getPid();
            String title = permission.getTitle();
            String icon = permission.getIcon();
            String href = permission.getHref();
            Boolean spread = permission.getOpen()==Constast.OPEN_TRUE?true:false;
            treeNodes.add(new TreeNode(id,pid,title,icon,href,spread));
        }
        //构造层级关系
        List<TreeNode> nodeList = TreeNodeBuilder.build(treeNodes, 1);
        return new DataGridView(nodeList);
    }

    /***菜单管理开始**/

    /**
     * 加载部门管理左边的树的json
     */
    @RequestMapping("loadMenuManagerLeftTreeJson")
    public DataGridView loadDeptManagerLeftTreeJson(SysPermissionVo permissionVo){
        QueryWrapper<SysPermission> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("type",Constast.TYPE_MENU);
        List<SysPermission> list = this.permissionService.list(queryWrapper);
        ArrayList<TreeNode> treeNodes = new ArrayList<>();
        for (SysPermission permission : list) {
            Boolean spread=permission.getOpen()==1?true:false;
            treeNodes.add(new TreeNode(permission.getId(),permission.getPid(),permission.getTitle(),spread));
        }
        return new DataGridView(treeNodes);
    }
    /**
     * 全查询
     */
    @RequestMapping("loadAllMenu")
    public DataGridView loadAllDept(SysPermissionVo permissionVo){
        IPage<SysPermission> page=new Page<>(permissionVo.getPage(),permissionVo.getLimit());

        QueryWrapper<SysPermission> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq(permissionVo.getId()!=null,"id",permissionVo.getId()).or().eq(permissionVo.getId()!=null,"pid",permissionVo.getId());
        queryWrapper.eq("type",Constast.TYPE_MENU);
        queryWrapper.like(StringUtils.isNotBlank(permissionVo.getTitle()),"title",permissionVo.getTitle());
        queryWrapper.orderByAsc("ordernum");

        this.permissionService.page(page,queryWrapper);

        return new DataGridView(page.getTotal(),page.getRecords());
    }

    /**
     * 添加菜单
     */
    @RequestMapping("addMenu")
    public ResultObj addDept(SysPermissionVo permissionVo){
        try {
            permissionVo.setType(Constast.TYPE_MENU);
            this.permissionService.save(permissionVo);
            return ResultObj.ADD_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }
    /**
     * 修改菜单
     */
    @RequestMapping("updateMenu")
    public ResultObj updateDept(SysPermissionVo permissionVo){
        try {
            this.permissionService.updateById(permissionVo);
            return ResultObj.UPDATE_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }


    /**
     * 加载最大的排序码
     */
    @RequestMapping("loadMaxMenuOrderNum")
    public Map<String,Object> loadMaxOrderNum(){
        HashMap<String, Object> map = new HashMap<>();

        QueryWrapper<SysPermission> queryWrapper=new QueryWrapper<>();
        queryWrapper.orderByDesc("ordernum");
        List<SysPermission> list = permissionService.list(queryWrapper);
        if (list.size()>0){
            map.put("value",list.get(0).getOrdernum()+1);
        }else {
            map.put("value",1);
        }

        return map;
    }

    /**
     * 检查是否含有子节点
     */
    @RequestMapping("checkChildrenNode")
    public Map<String,Object> checkChildrenNode(SysPermissionVo permissionVo){
        HashMap<String, Object> map = new HashMap<>();

        QueryWrapper<SysPermission> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("pid",permissionVo.getId());
        List<SysPermission> list = permissionService.list(queryWrapper);
        if (list.size()>0){
            map.put("value",true);
        }else {
            map.put("value",false);
        }

        return map;
    }

    /**
     * 删除菜单
     */
    @RequestMapping("deleteMenu")
    public ResultObj deleteDept(SysPermissionVo permissionVo){
        try {
            this.permissionService.removeById(permissionVo.getId());
            return ResultObj.DELETE_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }
    /***菜单管理结束**/
}
